package com.hnu.seckill.rabbitmq;


import com.hnu.seckill.entity.SeckillInfo;
import com.hnu.seckill.entity.TOrder;
import com.hnu.seckill.entity.TSeckillOrder;
import com.hnu.seckill.entity.TUser;
import com.hnu.seckill.service.ITGoodsService;
import com.hnu.seckill.service.ITOrderService;
import com.hnu.seckill.utils.JsonUtil;
import com.hnu.seckill.vo.GoodsVo;
import com.hnu.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    ITGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    ITOrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("Received message: {}", message);
        SeckillInfo seckillInfo = JsonUtil.jsonStr2Object(message, SeckillInfo.class);

        Long goodId = seckillInfo.getGoodsId();
        TUser user = seckillInfo.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVobyGoodsId(goodId);
        if(goodsVo.getStockCount()<1) {
            return;
        }
        TSeckillOrder seckillOrder = (TSeckillOrder) redisTemplate.opsForValue().get("seckillOrder:" + goodsVo.getId());
        if(seckillOrder!=null) {
//            model.addAttribute("errmsg", RespBeanEnum.REPEAT_ERROR.getMsg());
            return;
        }
        TOrder tOrder = orderService.secKill(user, goodsVo);
//        model.addAttribute("order", tOrder);
//        model.addAttribute("goods",goodsVo);


    }
}
